import os
import random
import string
import qrcode
from PIL import Image
from django.conf import settings
from urllib3.connectionpool import xrange


class QrcodeService():
    """
    二维码服务类
    """

    # 生成二维码
    def qrcode(self, strs, dir=None,logo=None,static='public/'):
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=1,
        )
        # 添加数据
        qr.add_data(strs)
        # 填充数据
        qr.make(fit=True)
        # 生成图片
        img = qr.make_image(fill_color="black", back_color="white")
        img = img.convert("RGBA")  # RGBA
        # 添加logo
        if logo:
            icon = Image.open(logo)
            # 获取图片的宽高
            img_w, img_h = img.size
            factor = 6
            size_w = int(img_w / factor)
            size_h = int(img_h / factor)
            icon_w, icon_h = icon.size
            if icon_w > size_w:
                icon_w = size_w
            if icon_h > size_h:
                icon_h = size_h
            # 重新设置logo的尺寸
            icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
            w = int((img_w - icon_w) / 2)
            h = int((img_h - icon_h) / 2)
            img.paste(icon, (w, h), icon)
        # 组装目录
        if not dir:
            re_path = static + 'qrcode/'
            dir = 'qrcode/'
        else:
            re_path = static + dir
        # 若目录不存在则创建
        m_dir = os.path.join(settings.BASE_DIR, re_path)
        if not os.path.exists(m_dir): os.mkdir(m_dir)
        name = self.randomString(16)
        ret = '/static/' + dir + name + ".png"
        img.save(m_dir + name + ".png")
        return ret

    # 生成随机字符串
    def randomString(self, len):
        random_list = []
        for i in xrange(len):
            random_list.append(random.choice(string.ascii_letters + string.digits))
        return ''.join(random_list)